/**
 * 
 * @param {*} arr 
 * @param {*} direction 
 * @param {*} debug 
 * @returns 
 */

/**
 * [2, 2, 2, 8]    'R' -> [0, 2, 4, 8]    'L' <- [4, 2, 8, 0]      'U' ^  [4]     'D'   [0]
 * [2, 0, 0, 0]                                                           [2]           [2]
 * [2, 0, 0, 0]                                                           [8]           [4]
 * [8, 0, 0, 0]                                                           [0]           [8]
 */

function ifDoMove1(arr, direction, debug = false) {
    const noZeroArr = arr.filter((item) => item > 0);
    // Do reverse, so that we can use same merge logic with other case. 
    // Be ware that result should reverse back as well
    if (direction == 'D' || direction == 'R') {
        noZeroArr.reverse();
    }

    const noZeroArrNew = [];
    let score = 0;
    let flag = false; // *生成的item不参与后面的计算
    let movable = false;

    noZeroArr.reduce((prev, curr, index) => {
        const len = prev.length;
        if (len > 0 && prev[len-1] === curr && !flag) {
            noZeroArrNew[len - 1] = curr * 2;
            score += curr * 2;
            flag = true;
            movable = true;
            if (debug) console.log('++  ', noZeroArrNew, curr);
        } else {
            noZeroArrNew.push(curr);
            flag = false;
        }
        return noZeroArrNew;
    }, []);

    // fill with 0
    const numToFill = 4 - noZeroArrNew.length;
    for (i=0; i<numToFill; i++) {
        noZeroArrNew.push(0);
    }

    // do reverse in case
    if (direction == 'D' || direction == 'R') {
        noZeroArrNew.reverse();
    }

    if (!movable) {
        for (i=0; i<3; i++) {
            if (noZeroArrNew[i] != arr[i]){
                movable = true;
                break;
            }
        }
    }

    return {
        arrNew: noZeroArrNew,
        direction,
        score,
        movable,
    };
}

console.log(ifDoMove([2, 2, 2, 8], 'R'));
console.log(ifDoMove([2, 2, 2, 8], 'L'));
console.log(ifDoMove([2, 2, 2, 8], 'U'));
console.log(ifDoMove([2, 2, 2, 8], 'D'));


console.log(ifDoMove([2, 4, 2, 2], 'R'));
console.log(ifDoMove([2, 4, 2, 2], 'L'));
console.log(ifDoMove([2, 4, 2, 2], 'U'));
console.log(ifDoMove([2, 4, 2, 2], 'D'));

console.log(ifDoMove([2, 2, 2, 2], 'R'));
console.log(ifDoMove([2, 2, 2, 2], 'L'));
console.log(ifDoMove([2, 2, 2, 2], 'U'));
console.log(ifDoMove([2, 2, 2, 2], 'D'));

console.log(ifDoMove([0, 2, 2, 0], 'R'));
console.log(ifDoMove([0, 2, 2, 0], 'L'));
console.log(ifDoMove([4, 2, 2, 0], 'U'));
console.log(ifDoMove([4, 2, 2, 0], 'D'));
